#!/bin/bash
# 用途：监控远程主机的磁盘使用情况

LOG_FILE="disk_usage.log"
if [[ -n $1 ]];
then
	LOG_FILE=$1
fi

if [ ! -e $LOG_FILE ];
then
	printf "%-8s %-14s %-9s %-8s %-6s %-6s %-6s %-20s %s\n" \
	"Date" "IP address" "Device" "Capacity" "Used" "Free" "Precent" "Mount"  "Status" > $LOG_FILE
fi

IP_LIST="127.0.0.1 168.92.0.1"          #监控主机IP地址列表
USER_NAME="test"                        #登入远程主机所用用户名
TEMP_FILE=/tmp/$$.df                    #临时文件
ALARM_THRESHOLD=80                      #告警阀值，磁盘使用到达80则显示不安全

(
for IP in $IP_LIST;
do
	if [ ! -f $TEMP_FILE ];
	then 
		touch $TEMP_FILE 2>/dev/null
		if [ $? -eq 0 ]
		then
			echo
		else
			echo "touch temp file failed!"
			exit 1 
		fi
	fi
	
	ssh $USER_NAME@$IP 'df -h' | grep ^/dev/ > $TEMP_FILE 
	while read LINE;
	do
		CURRENT_DATE=$(date +%D);
		printf "%-8s %-14s " "$CURRENT_DATE" "$IP";
		echo $LINE | awk '{printf(%-9s %-8s %-6s %-6s %-8s %-20s",$1, $2, $3, $4, $5, $6);}';

		#标识磁盘状态，80%以下，显示SAFE，以上显示ALERT
		PUSG=$(echo $LINE | egrep -o "[0-9]+%");
		PUSG=${PUSG/\%/};
		if [ $PUSG -lt $ALARM_HTRESHOLD ];
		then
			echo SAFE
		else
			echo ALERT
		fi
	done < $TEMP_FILE 
done
) >> $LOG_FILE
